package customermanagesystem.demo.controller;

//packamege custormanagesystem.demo.controller;
//contentType: 'application/json;charset=UTF-8',
//后端要加@Requestbody注解
import customermanagesystem.demo.bean.Customer;
import customermanagesystem.demo.bean.DataTablesOutput;
import customermanagesystem.demo.dao.CustomerMapper;
import customermanagesystem.demo.service.CustomerService;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@RequestMapping("/customer") //url地址映射
@Controller //该类被IOC容器管理

public class CMSController {
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private CustomerService customerService;

    @PostMapping("/query")
    @ResponseBody //返回json数据给前端
    public DataTablesOutput getCustomers( Customer customer, Integer start, Integer length, Integer draw, Integer recordsTotal){
       Object session= request.getSession().getAttribute("user");
       if(session==null){}
       if(session!=null) {
//           List<Customer> customers = customerMapper.queryCustomer(customer,start,length);
//           return customers;
           return customerService.queryCustomer(customer,start,length,draw,recordsTotal);
       }
        return null;
    }

//    @PostMapping("/query")
//    @ResponseBody //返回json数据到前端
//    public DataTablesOutput getCustomer(Customer customer, Integer start, Integer length, Integer draw, Integer recordsTotal) {
//
//        return customerService.queryCustomer(customer, start, length, draw, recordsTotal);
//
//    }

//    @GetMapping
//    @ResponseBody
//    public void test(@RequestBody Customer customer){
//        System.out.println("前端传来的参数："+customer);
//    }

    @PutMapping
    @ResponseBody
    public void modifyCustomer(@RequestBody Customer customer){
        customerMapper.modifyCustomer(customer);
    }

    @DeleteMapping
    @ResponseBody
    public void delCustomer(int id){
        customerMapper.delCustomer(id);
    }

//    @PostMapping
//    @ResponseBody
//    public void addCustomer(@RequestBody Customer customer){
//        String fileName=UUID.randomUUID()+"_"+customer.getPhotoName();
//        getUrl(customer.getCustPhoto(),fileName);
//        customer.setCustPhoto(fileName);
//        customerMapper.addCustomer(customer);
//    }
@PostMapping("/addCustomer")
@ResponseBody
public String addCustomer(Customer customer, MultipartFile file) throws IOException {
    String filename=UUID.randomUUID()+"_"+file.getOriginalFilename();
    System.out.println(filename);
    File dirs=new File("src/main/resources/static/images/"+filename);
//        }
    if (file.isEmpty()){
        customerMapper.addCustomer(customer);
        return "图片上传失败！";
    }else {
        file.transferTo(new File(dirs.getAbsolutePath()));
//            IOUtils.copy(inputStream, out);
        customer.setCustPhoto("/static/images/"+filename);
        customerMapper.addCustomer(customer);
        return "添加成功！";
    }
}


    @PostMapping("/count")
    @ResponseBody //返回json数据到前端
    public int getCustomerCount(@RequestBody Customer customer) {
        return customerService.queryTotalCount(customer);
    }

//    @PostMapping("/show")
//    @ResponseBody //返回json数据到前端
//    public int getCustomerPhoto(@RequestBody Customer customer) {
//        return customerService.queryPhoto(customer);
//    }

    @PostMapping("/formUpload")
    @ResponseBody
    public String formUpload(MultipartFile form, HttpServletRequest request)  {
        //获取完整的文件名称
        String newFileName= UUID.randomUUID()+ "_"+form.getOriginalFilename();// 获取项目名称,文件上传位置
        File dirs=new File("src/upload");
        if(!dirs.exists()){
            dirs.mkdirs();// 不存在路径则进行创建
        }
        String filePath = dirs.getAbsolutePath()+File.separator+newFileName; //文件路径
        try {
            //最好写绝对路径
            form.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new File(filePath).getAbsolutePath();
    }



//    public void getUrl(String base64String,String fileName){
//        base64String = base64String.split(":")[0];//去掉base64码的data:image/png;base64,
//        System.out.println(base64String);
//        BASE64Decoder decoder = new BASE64Decoder();
//        try {
//            // Base64解码
//            byte[] bytes = decoder.decodeBuffer(base64String);
//            // 生成jpeg图片
//            FileUtils.writeByteArrayToFile(new File(fileName),bytes);
//        } catch (Exception e) {
//            System.out.println(e);
//        }
//    }

    public HSSFWorkbook downloadExcel(List<Customer> customers){
        String [] excelHeader={"custId","custName","custIndustry","custLevel","custMobile","custCreatTime"};

        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet("客户表");
        HSSFRow row=sheet.createRow((int)0);
        HSSFCellStyle style=workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //单元格式
        for(int i=0;i<excelHeader.length;i++){//设置列宽
            HSSFCell cell=row.createCell(i);
            cell.setCellValue(excelHeader[i]);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(cell.getColumnIndex(),90*60);
        }
        for(int i=0;i<customers.size();i++){
            row=sheet.createRow(i+1);
            Customer customer=customers.get(i);
            row.createCell(0).setCellValue(customer.getCustId());
            row.createCell(1).setCellValue(customer.getCustName());
            row.createCell(2).setCellValue(customer.getCustIndustry());
            row.createCell(3).setCellValue(customer.getCustLevel());
            row.createCell(4).setCellValue(customer.getCustMobile());
            row.createCell(5).setCellValue(customer.getCustCreateTime());
        }
        return  workbook;

    }
    @GetMapping("/download")
    public void  downloadExcel(HttpServletResponse response) throws IOException {
        List<Customer> customers=customerMapper.queryCustomer(new Customer(),1,1000);
        System.out.println(customers);
        CMSController cmsController=new CMSController();
        HSSFWorkbook wb=cmsController.downloadExcel(customers);
        OutputStream outputStream=response.getOutputStream();

        String fileName="excel"+".xls";
        fileName= URLEncoder.encode(fileName,"UTF-8");
        response.setHeader("Content-disposition","attachment;filename"+fileName+";"+"filename*=utf-8''"+fileName);
        wb.write(outputStream);
        outputStream.close();
    }

    //参数都在url请求上，放在请求体里面怎么做
    //默认不设置contentType：application/x-www-form-url
    //参数按照key=value发送
    //接受一个参数 基本数据类型 Integer id
    //前端:1、"/test?id="+1 2、data:'id='+'2',
    //3、data:{'id':'2'},
    //一个要求，前端key名字和后端入参参数名字保持一致
    //@ReqParam 可以省略 key和参数名不一致需要添加这个
    //多个参数：预期接受换成一个对象给我
    //springMVC 转成customer
    //第一步：创建一个空对象 第二步：custId=2&custName=zs
    //第三步：setCustName（custName）zs
    //后端接收数组：int[] ids 前端：'ids='+ids,


}
